package utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.SQLException;

public class MyDataSourceUtils {
//	获取Connection ---- 从连接池中获取
	private static ComboPooledDataSource dataSource = new ComboPooledDataSource();

//	创建一个ThreadLocal
	public static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

//	开启事务
	public static void starTransaction() throws SQLException {
		Connection conn = getCurrentConnection();
		conn.setAutoCommit(false);
	}

//	获得当前线程上绑定的conn
	public static Connection getCurrentConnection() throws SQLException {

		//		从ThreadLocal寻找当前线程是否有对应的Connection
		Connection conn = tl.get();
		if (conn == null){
//			获得一个新Connection
			conn = getConnection();
//			将conn资源绑定到ThreadLocal(map)上
			tl.set(conn);
		}
		return conn;
	}

	//创建一个线程
	public static Connection getConnection() throws SQLException {
	return dataSource.getConnection();
	}

//回滚事务
	public static void rollback() throws SQLException {
		getCurrentConnection().rollback();
	}

//	提交事务
	public static void commit() throws SQLException {
		Connection conn = getCurrentConnection();
		conn.commit();
//		将事务从ThreadLocal里面移除
		tl.remove();
//		关闭连接
		conn.close();
	}
}
